package com.vshop.controller.other;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.interfacerequest.verify.request.RequestVerify;
import com.vshop.entity.interfacerequest.verify.request.RequestVerifyData;
import com.vshop.entity.interfacerequest.verify.request.RequestVerifyTradeData;
import com.vshop.entity.interfacerequest.verify.response.ResponseVerify;
import com.vshop.entity.interfacerequest.verify.response.ResponseVerifyData;
import com.vshop.entity.interfacerequest.verify.response.ResponseVerifyTradeData;
import com.vshop.entity.requestinterface.Constant;
import com.vshop.entity.requestinterface.userlogin.request.UserLoginRequest;
import com.vshop.entity.requestinterface.userlogin.response.UserLoginResponse;
import com.vshop.service.SequenceService;
import com.vshop.utils.HttpUtil;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 验证deviceCode的有效性
 *
 * @author lm
 * @date 2019/03/07
 */
@RestController
@Api(description = "验证deviceCode的有效性")
@Slf4j
public class VerifyDeviceCodeController {
    @Autowired
    private SequenceService sequenceService;

    /**
     * 直接请求网关xml接口的地址
     */
    @Value("${iot.requestURI}")
    private String requestURI;

    @CrossOrigin
    @PostMapping(value = "verify", produces = "application/json;charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "验证deviceCode的有效性", response = ResponseVerify.class)
    public String verify(@ApiParam @RequestBody RequestVerify request) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;

        ExceptionRequest utils = new ExceptionRequest();
        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("前端请求：" + requestStr);
            RequestVerify requestPackage = JSONArray.parseObject(requestStr, RequestVerify.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                log.info("请求的签名是：" + requestSign);
                RequestVerifyData requestData = requestPackage.getData();

                if (requestPackage.getData() == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    String version = requestData.getVersion();
                    List<RequestVerifyTradeData> requestTradeData = requestData.getTradeData();

                    if (StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || lang == null || version == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 将请求体json转成String
                        String str = JSON.toJSONString(requestData);
                        // 将Str拿去计算签名
                        String sign = utils.calculateSignature(str);
                        log.info("计算的签名是：" + sign);
                        if (!requestSign.equalsIgnoreCase(sign)) {
                            log.info("签名验证失败！");
                            jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                            return jsonString;
                        } else {//签名验证通过
                            List<ResponseVerifyTradeData> tradeDataList = new ArrayList<ResponseVerifyTradeData>();
                            ResponseVerifyTradeData tradeData = null;

                            for (RequestVerifyTradeData v : requestTradeData) {
                                String deviceCode = v.getDeviceCode();

                                if (StringUtils.isNotBlank(deviceCode)) {

                                    //用deviceCode去iot网关查询企业编码
                                    UserLoginRequest user = new UserLoginRequest();
                                    user.setDeviceId(deviceCode);
                                    //组装需要的json去请求报文
                                    String requestInterface = JSON.toJSONString(user);
                                    log.info("请求北京的接口请求报文：" + requestInterface);
                                    String url = requestURI + Constant.iot_queryPartner_2;
                                    // 发送post请求，并接收返回结果
                                    String returnStr = HttpUtil.httpPost(url, requestInterface);
                                    log.info("北京回复的下发接口响应报文：" + returnStr);
                                    UserLoginResponse response = JSONArray.parseObject(returnStr, UserLoginResponse.class);

                                    if (response != null) {
                                        if (true == Constant.RET_CODE_0000.equalsIgnoreCase(response.getRetCode())) {
                                            String partnerCodes = response.getPartnerCode();

                                            if (partnerCode.equals(partnerCodes)) {
                                                log.info("成功");
                                                tradeData = new ResponseVerifyTradeData();
                                                tradeData.setDeviceCode(deviceCode);
                                                tradeData.setTradeRstCode("0000");
                                                if (lang.equals("cn") || StringUtils.isBlank(lang)) {
                                                    tradeData.setTradeRstMessage("成功");
                                                } else {
                                                    tradeData.setTradeRstMessage("success");
                                                }
                                                tradeDataList.add(tradeData);

                                            } else {
                                                log.info("卡号与渠道不匹配");
                                                tradeData = new ResponseVerifyTradeData();
                                                tradeData.setDeviceCode(deviceCode);
                                                tradeData.setTradeRstCode("0008");
                                                if (lang.equals("cn") || StringUtils.isBlank(lang)) {
                                                    tradeData.setTradeRstMessage("卡号与企业不匹配");
                                                } else {
                                                    tradeData.setTradeRstMessage("The card number does not match partnerCode");
                                                }
                                                tradeDataList.add(tradeData);
                                            }

                                        } else {

                                            String retCode = response.getRetCode();
                                            String retInfo = response.getResultInfo();

                                            tradeData = new ResponseVerifyTradeData();
                                            tradeData.setDeviceCode(deviceCode);
                                            tradeData.setTradeRstCode(retCode);
                                            if (lang.equals("cn") || StringUtils.isBlank(lang)) {
                                                if (retCode.equals("0061")) {
                                                    tradeData.setTradeRstMessage("无此设备！");
                                                } else if (retCode.equals("0062")) {
                                                    tradeData.setTradeRstMessage("设备号无效！");
                                                } else {
                                                    tradeData.setTradeRstMessage(retInfo);
                                                }
                                            } else {
                                                if (retCode.equals("0061")) {
                                                    tradeData.setTradeRstMessage("No equipment!");
                                                } else if (retCode.equals("0062")) {
                                                    tradeData.setTradeRstMessage("Invalid deviceCode!");
                                                } else {
                                                    tradeData.setTradeRstMessage(retInfo);
                                                }
                                            }
                                            tradeDataList.add(tradeData);


                                        }


                                    } else {
                                        log.info("接口出现异常");
                                        tradeData = new ResponseVerifyTradeData();
                                        tradeData.setDeviceCode(deviceCode);
                                        tradeData.setTradeRstCode("9999");
                                        if (lang.equals("cn") || StringUtils.isBlank(lang)) {
                                            tradeData.setTradeRstMessage("接口异常");
                                        } else {
                                            tradeData.setTradeRstMessage("Interface handles exceptions or returns errors!");
                                        }
                                        tradeDataList.add(tradeData);

                                    }
                                } else {
                                    ResponseVerifyData data = new ResponseVerifyData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setTradeTime(curtime);
                                    data.setTradeType(tradeType);
                                    data.setTradeData(tradeDataList);
                                    data.setTradeRstCode("0060");
                                    if (lang.equals("cn") || StringUtils.isBlank(lang)) {

                                        data.setTradeRstMessage("deviceCode 不能为空");
                                    } else {
                                        data.setTradeRstMessage("deviceCode cannot be empty");
                                    }

                                    ResponseVerify response = new ResponseVerify();
                                    response.setData(data);
                                    response.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));

                                    jsonString = JSON.toJSONString(response);
                                    log.info("响应报文：" + jsonString);
                                    return jsonString;

                                }


                            }

                            ResponseVerifyData data = new ResponseVerifyData();
                            data.setConnSeqNo(ConnSeqNo);
                            data.setPartnerCode(partnerCode);
                            data.setTradeTime(curtime);
                            data.setTradeType(tradeType);
                            data.setTradeData(tradeDataList);
                            data.setTradeRstCode("0000");
                            if (lang.equals("cn") || StringUtils.isBlank(lang)) {

                                data.setTradeRstMessage("成功");
                            } else {
                                data.setTradeRstMessage("success");
                            }

                            ResponseVerify response = new ResponseVerify();
                            response.setData(data);
                            response.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));

                            jsonString = JSON.toJSONString(response);
                            log.info("响应报文：" + jsonString);
                            return jsonString;

                        }
                    }
                }
            }
        }
    }
}